package cn.i96688.scanclient.bean;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PayLog {
	public boolean cache=true;
	List<String> logs=new ArrayList<String>();
	private SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private final int maxSize=100;
	
	private static PayLog instance=new PayLog();
	public static PayLog getInstance(){
		return instance;
	}
	
	public void addLog(String msg){
		String date=dateFormat.format(new Date(System.currentTimeMillis()));
		StringBuilder sb=new StringBuilder().append(date).append(" - ").append(msg);
		if(cache){
			logs.add(sb.toString());
			//多余数据
			int clear=logs.size()-maxSize;
			for(int i=0;i<clear;i++){
				logs.remove(0);
			}
		}
		System.out.println(sb.toString());
	}
	
	public void addLogs(Throwable e){
		StringWriter sw=new StringWriter();
		PrintWriter pw=new PrintWriter(sw);
		e.printStackTrace(pw);
		addLog(sw.toString());
	}
	public List<String> getLogs(){
		return logs;
	}
	public void exportLog(String filePath){
		FileOutputStream fos=null;
		OutputStreamWriter writer = null;
		try {
			fos=new FileOutputStream(filePath);
			writer=new OutputStreamWriter(fos, "UTF-8");
			for(String str:logs){
				writer.write(str+"\n");
			}
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(fos!=null)
					fos.close();
			} catch (Exception e2) {
			}
			try {
				if(writer!=null)
					writer.close();
			} catch (Exception e2) {
			}
		}
	}
}
